package com.pignest.hotel.ajax;

import com.pignest.framework.ajax.BaseAjax;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.beans.global.ClientSession;
import com.pignest.hotel.system.AuthenticatorHolder;
import com.pignest.hotel.system.Key;
import com.pignest.hotel.system.Permission;
import com.pignest.hotel.system.exception.AjaxException;

public abstract class HotelAjax extends BaseAjax {

	public HotelAjax() {
		ClientSession cs = (ClientSession)getSession().getAttribute(Key.CLIENT_SESSION);
		if (cs != null) {
			AuthenticatorHolder.setClientSession(cs);
		}
	}
	
	protected User getCurrentUser() {
		ClientSession session = getClientSession();
		return session == null ? null : session.getUser();
	}
	
	protected User getCurrentUser(Permission p) {
		User user = getCurrentUser();
		if (p == null)
			return user;
		if (user == null)
			return null;
		if (!p.alow(user))
			return null;
		return user;
	}
	
	protected boolean hasPermission(Permission p) {
		User user = getCurrentUser();
		if (p == null)
			return true;
		if (user == null)
			return false;
		return p.alow(user);
	}
	
	protected void checkPermission(Permission p) {
		if (p == null)
			return;
		User user = getCurrentUser();
		if (user == null)
			noPermission(true);
		if (!p.alow(user))
			noPermission(false);
	}
	
	/** 多个权限, 只要有一个就可以 */
	protected void checkPermissionOr(Permission... p) {
		if (p == null || p.length == 0)
			return;
		User user = getCurrentUser();
		if (user == null)
			noPermission(true);
		for (int i = 0; i < p.length; i++) {
			if (p[i].alow(user))
				return;
		}
		noPermission(false);
	}
	
	/** 多个权限, 每个都必须有*/
	protected void checkPermissionAnd(Permission... p) {
		if (p == null || p.length == 0)
			return;
		User user = getCurrentUser();
		if (user == null)
			noPermission(true);
		for (int i = 0; i < p.length; i++) {
			if (!p[i].alow(user))
				noPermission(false);
		}
	}
	
	private void noPermission(boolean login) {
		throw new AjaxException(login ? "请重新登录后重试" : "你未被授权");
	}
	
	protected void error(String msg) {
		throw new AjaxException(msg);
	}
	
	protected ClientSession getClientSession() {
//		return super.getClientSession();
		return (ClientSession)getRequest().getSession().getAttribute(Key.CLIENT_SESSION);
	}
}
